package com.sky.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@Slf4j
public class RedisConfiguration {

	/**
	 * redisTemplate配置
	 * @param redisConnectionFactory redis连接工厂
	 * @return RedisTemplate
	 */
	@Bean(name = "redisTemplate")
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		log.info("开始创建Redis模板对象......");
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
		//设置Redis的连接工厂对象
		redisTemplate.setConnectionFactory(redisConnectionFactory);
		// String的序列化
		StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
		// JSON序列化配置
		Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
		jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

		//设置Redis key的序列化器 string
		redisTemplate.setKeySerializer(stringRedisSerializer);
		// 设置Redis value的序列化类型 json
//		redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
		// 设置Redis hash key 的序列化器
		redisTemplate.setHashKeySerializer(stringRedisSerializer);
		// 设置Redis hash value的序列化类型 json
//		redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

		redisTemplate.afterPropertiesSet();

		return redisTemplate;

	}

}


